<?php

namespace app\admin\controller\business;

use app\admin\model\SystemAdmin;
use app\common\controller\AdminController;
use app\common\model\BusinessDistrict;
use app\common\model\BusinessDistrictAdmin;
use app\common\model\PointsLog;
use app\common\model\Shop;
use app\common\model\User;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="商圈表")
 */
class District extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\BusinessDistrict();

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where, $extra) = $this->buildTableParames();
            //var_export($extra);
//            $where[] = ['u.role', '=', 3];
//            if (isset($extra['admin_account'])) {
//                $where[] = ['sa.username', '=', $extra['admin_account']];
//            }
//            if (isset($extra['user_id'])) {
//                $where[] = ['u.id', '=', $extra['user_id']];
//            }
            $count = $this->model->alias('d')
                ->where($where)
                ->count();
            $list = $this->model->alias('d')
                ->where($where)
                ->field('d.*')
                ->page($page, $limit)
                ->order('d.id desc')
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'phone' => 'require',
                'type'  => 'require',
            ];
            $this->validate($post, $rule);
            $user = User::where('phone', $post['phone'])->find();
            if (!$user) {
                $this->error('用户不存在');
            }
            $re = BusinessDistrictAdmin::alias('da')
                ->join('pm_business_district d', 'da.district_id = d.id', 'right')
                ->where('da.user_id', $user->id)
                ->where('d.type', $post['type'])
                ->find();
            if ($re) {
                $this->error('用户已在其他商圈中有角色');
            }
            Db::startTrans();
            try {
                $district = BusinessDistrict::create([
                    'name' => $post['name'],
                    'type' => $post['type'],
                ]);
                BusinessDistrictAdmin::create([
                    'district_id'  => $district->id,
                    'user_id'      => $user->id,
                    'role'         => 1,
                    'function_arr' => '1,2,3,4',
                    'status'       => 1
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败:'.$e->getMessage());
            }
            $this->success('保存成功');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->alias('d')
            ->where(['d.id' => $id])
            ->field('d.*')->find();
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);

            Db::startTrans();
            try {
                BusinessDistrict::where('id', $id)->update([
                    'name' => $post['name']
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败');
            }
            $this->success('保存成功');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * 商圈结算
     *
     *
     * 结算页面 数据展示
     * 以及数据结算
     */
    public function settlement($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);

            if ($row->points_one == 0) {
                $this->error('当前店铺不需要结算');
            }
            Db::startTrans();
            try {
                $num = $row->points_one;
                //店铺增加积分变动记录
                if ($num < 0) {
                    //需要补充店铺积分
                    //商户增加积分记录
                    PointsLog::create([
                        'form_user_id'   => 0,
                        'user_id'        => 0,
                        'shop_id'        => $row->id,
                        'num'            => -$num,
                        'type'           => 4,
                        'flag'           => 3,
                        'relation_id'    => 0,
                        'relation_sheet' => 0,
                    ]);
                } else {
                    PointsLog::create([
                        'form_user_id'   => 0,
                        'user_id'        => 0,
                        'shop_id'        => $row->id,
                        'num'            => $num,
                        'type'           => 5,
                        'flag'           => 4,
                        'relation_id'    => 0,
                        'relation_sheet' => 0,
                    ]);
                }
                //店铺积分归零
                $row->points_one = 0;
                $row->save();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败：'.$e->getMessage());
            }
            $this->success('保存成功');
        }
        //当前店铺 积分重新计算
        //统计店铺积分
        //店铺总共发出去的积分数量
        //总共发出的积分
        $sendNum = PointsLog::where('shop_id', $id)
            ->where('type', 'in', [1, 5])
            ->sum('num');

        //总共收入积分
        $incomeNum = PointsLog::where(function ($query) use ($id) {
            $query->where(['shop_id' => $id, 'goods_shop_id' => 0])->whereOr('goods_shop_id', $id);
        })
            ->where('type', 'in', [2, 4])
            ->sum('num');
        $num = $incomeNum - $sendNum;
        $row->points_one = $num;
        $row->save();
        $this->assign('send_num', $sendNum);
        $this->assign('income_num', $incomeNum);
        $this->assign('num', $num);
        $this->assign('row', $row);
        return $this->fetch();
    }

}